package com.yswy.common.wxOrder.V3.wxPayV3Transfer;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.oss.ServiceException;
import com.google.gson.Gson;
import com.yswy.common.utils.OrderNoCenter;
import com.yswy.common.utils.StringUtils;
import com.yswy.common.wxOrder.V3.WxPayConfigV3;
import com.yswy.common.wxOrder.V3.wxPayV3Search.WxchatCallbackSuccessData;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Slf4j
public class WxPaySearchTransfreUtil {



    public static void main(String[] args) {
        WxPayConfigV3 wxPayConfig = new WxPayConfigV3();
        wxPayConfig.setMchId("1645167139");// 商户号
        wxPayConfig.setMchSerialNo("5C652203771D07ECB38C5255C18FC4D8A6994EA9");// 商户API证书序列号
        wxPayConfig.setPrivateKeyPath("C:\\Users\\mxy\\Desktop\\wxkey\\1645167139\\apiclient_key.pem");// 商户私钥文件
        wxPayConfig.setCertificateKeyPath("C:\\Users\\mxy\\Desktop\\wxkey\\1645167139\\wechatpay_6BFC5613CA7AE0DBBA924E1C85310DFF47FEB050.pem");
        wxPayConfig.setKey("0F1151762C973622D1D9DEBF516671B2");// APIv3密钥
        wxPayConfig.setAppid("wxd5b74c5ae85bc51e");// APPID
        wxPayConfig.setDomain("https://api.mch.weixin.qq.com"); // 微信服务器地址
        wxPayConfig.setNotifyDomain("https://bkservice.dyh2024.top/payOrder/callbackOrder");// 接收结果通知地址




        TransferBatch s = searchByOrderId(wxPayConfig,"202308281755011782583296",wxPayConfig.getWxPayClient());

        System.out.println("transferBatches:"+s);
    }

    /**
     * 根据微信支付系统生成的订单号查询订单详情
     * @param wxPayConfig 微信支付配置信息
     * @param orderId 我们自己的订单id
     * @param wxPayClient 微信支付客户端请求对象
     * @return 微信订单对象
     */
    public static TransferBatch searchByOrderId(WxPayConfigV3 wxPayConfig, String orderId, CloseableHttpClient wxPayClient) {
        // 1.请求路径和对象
        String url = wxPayConfig.getDomain().concat("/v3/transfer/batches/out-batch-no/")
                .concat(orderId).concat("?need_query_detail=true&detail_status=ALL");
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("Accept", "application/json");

        // 2.完成签名并执行请求
        CloseableHttpResponse response = null;
        try {
            response = wxPayClient.execute(httpGet);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("微信支付请求失败");
        }

        // 3.解析返回的数据
        TransferBatch callbackData = resolverResponse(response);
        log.info("callbackData:{}",callbackData);
        return callbackData;
    }


    /**
     * 解析响应数据
     * @param response 发送请求成功后，返回的数据
     * @return 微信返回的参数
     */
    private static TransferBatch resolverResponse(CloseableHttpResponse response) {
        try {
            // 1.获取请求码
            int statusCode = response.getStatusLine().getStatusCode();
            // 2.获取返回值 String 格式
            final String bodyAsString = EntityUtils.toString(response.getEntity());

            Gson gson = new Gson();
            if (statusCode == 200) {
                // 3.如果请求成功则解析成Map对象返回
//                HashMap<String, String> resultMap = gson.fromJson(bodyAsString, HashMap.class);
                JSONObject resultMap = JSONObject.parseObject(bodyAsString);
                JSONObject transfer_batch = resultMap.getJSONObject("transfer_batch");
                JSONArray transfer_detail_list = resultMap.getJSONArray("transfer_detail_list");



                // 4.封装成我们需要的数据
                TransferBatch transferBatch = new TransferBatch();
                transferBatch.setMchid(transfer_batch.getString("mchid"));
                transferBatch.setOut_batch_no(transfer_batch.getString("out_batch_no"));
                transferBatch.setBatch_id(transfer_batch.getString("batch_id"));
                transferBatch.setAppid(transfer_batch.getString("appid"));
                transferBatch.setBatch_status(transfer_batch.getString("batch_status"));
                List<TransferDetail> transferDetailList = new ArrayList<>();
                if (transfer_detail_list != null && transfer_detail_list.size()>0){
                    for (Object js:transfer_detail_list) {
                        JSONObject transfer_detail = JSONObject.from(js);
                        TransferDetail transferDetail = new TransferDetail();
                        transferDetail.setDetail_id(transfer_detail.getString("detail_id"));
                        transferDetail.setOut_detail_no(transfer_detail.getString("out_detail_no"));
                        transferDetail.setDetail_status(transfer_detail.getString("detail_status"));
                        transferDetailList.add(transferDetail);
                    }
                }
                transferBatch.setTransferDetailList(transferDetailList);
                return transferBatch;
            } else {
                if (StringUtils.isNoneBlank(bodyAsString)) {
                    log.error("微信支付请求失败，提示信息:{}", bodyAsString);
                    // 4.请求码显示失败，则尝试获取提示信息
                    HashMap<String, String> resultMap = gson.fromJson(bodyAsString, HashMap.class);
                    throw new ServiceException(resultMap.get("message"));
                }
                log.error("微信支付请求失败，未查询到原因，提示信息:{}", response);
                // 其他异常，微信也没有返回数据，这就需要具体排查了
                throw new IOException("request failed");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e.getMessage());
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
